import {messages} from "share/common";
import React from 'react';
import { connect } from 'react-redux'
import config from 'config'
import {Button, Modal, Popover, Tabs} from 'antd'
const TabPane = Tabs.TabPane;
import httpFetch from 'share/httpFetch'
import UploadFileSection from './upload-template'
import UploadResultSection from './upload-result'
import 'styles/components/template/importer.scss'

//数据导入组件
class Importer extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      modalVisible: false,
      fileList: [],
      tabKey: 'TEMPLATE',
      uploadResult: {},
      errorData: [],
      importResponse: {},  //导入文件时获得的后端数据，下载错误文件时传过去
      transactionOID: '',
      page: 0,
      total: 0
    };
  }

  handleOk = () => {
    const { tabKey, transactionOID } = this.state;
    const { onOk } = this.props;
    //在导入tab下为上传
    if(tabKey === 'TEMPLATE') {
      this.uploadFileSectionRef.onUpload();
    } else {
      this.setState({ modalVisible: false });
      onOk && onOk(transactionOID);
    }
  };

  onCancel = () => {
    const { tabKey, transactionOID } = this.state;
    const { onOk } = this.props;
    this.setState({ modalVisible: false, page: 0, total: 0 });
    if(tabKey === 'TEMPLATE' && transactionOID) {
      httpFetch.delete(`${config.budgetUrl}/api/budget/batch/transaction/logs/${transactionOID}`);
      this.uploadFileSectionRef._clearTimeout();
    }
    tabKey === 'RESULT' && onOk && onOk(transactionOID);
  };

  handleAfterClose = () => {
    const { transactionOID } = this.state;
    const { modalOptions: { afterClose } } = this.props;
    this.setState({
      tabKey: 'TEMPLATE',
      uploading: false,
      fileList: [],
      page: 0,
      total: 0
    });
    afterClose && afterClose(transactionOID);
  };

  onChange = params => this.setState({ ...Object.assign({}, this.state, params) });

  onChangeErrorTable = current => {
    const { transactionOID } = this.state;
    this.setState({ page: current - 1}, () => this.uploadFileSectionRef.listenStatus(transactionOID));
  };

  openModal = () => this.setState({ modalVisible: true });

  render() {
    const { modalOptions: { title, visible, afterClose, ...rest }, template, templateOptions, uploadOptions, infoMessage,
      asyncMode, asyncModeMessage, uploadResultOptions, onConfirmUpload, beforeUpload, btnProps, btnName, triggerNode,
      onValidate, errorTableData, totalError, errorColumns, parseUploadResult } = this.props;
    const { modalVisible, uploading, tabKey, uploadResult, errorData, transactionOID, fileList, total, page, importResponse } = this.state;
    return (
      <div style={{display: 'inline-block'}}>
        {
          triggerNode ?
            Object.prototype.toString.call(triggerNode).indexOf('Array') > -1 ?
              triggerNode.map(node => React.cloneElement(node, {
                onClick: e => {
                  this.openModal();
                  node.props.onClick && node.props.onClick(e);
                }
              })) :
              React.cloneElement(triggerNode, {
                onClick: e => {
                  this.openModal();
                  triggerNode.props.onClick && triggerNode.props.onClick(e);
                }
              })
            :
            <Button
              {...btnProps}
              onClick={e => {
                this.openModal();
                btnProps.onClick && btnProps.onClick(e);
              }}
            >{btnName}</Button>
        }
        <Modal
          title={title}
          width={760}
          className="importer-v2"
          visible={modalVisible}
          afterClose={this.handleAfterClose}
          onCancel={this.onCancel}
          confirmLoading={uploading}
          footer={[
            tabKey === 'TEMPLATE' && <Button key="cancel"  onClick={this.onCancel}>{messages('common.cancel')/*取消*/}</Button>,
            <Button
              type={tabKey === 'TEMPLATE' ? 'primary' : ''}
              key="submit"
              loading={uploading}
              onClick={this.handleOk}
            >
              {tabKey === 'TEMPLATE' ? messages('common-1.key375')/*导 入*/ : messages('common-1.key41')/*关闭*/}
            </Button>
          ]}
          {...rest}
        >
          <Tabs defaultActiveKey="TEMPLATE" activeKey={tabKey} >
            <TabPane
              tab={messages('common-1.key370')/*上传文件*/}
              key="TEMPLATE"
              disabled={tabKey === 'RESULT'}
            >
              <UploadFileSection
                onRef={ref => this.uploadFileSectionRef = ref}
                infoMessage={infoMessage}
                template={template}
                templateOptions={templateOptions}
                uploadOptions={uploadOptions}
                onChange={this.onChange}
                onConfirmUpload={onConfirmUpload}
                onValidate={onValidate}
                beforeUpload={beforeUpload}
                errorTableData={errorTableData}
                totalError={totalError}
                fileList={fileList}
                page={page}
                asyncMode={asyncMode}
              />
            </TabPane>
            <TabPane
              tab={messages('common-1.key376')/*导入结果*/}
              key="RESULT"
              disabled={tabKey === 'TEMPLATE'}
            >
              <UploadResultSection
                asyncMode={asyncMode}
                asyncModeMessage={asyncModeMessage}
                uploadResult={uploadResult}
                importResponse={importResponse}
                errorData={errorData}
                pagination={{
                  total,
                  pageSize: 10,
                  current: page + 1,
                  onChange: this.onChangeErrorTable
                }}
                uploadResultOptions={uploadResultOptions}
                transactionOID={transactionOID}
                onChange={this.onChange}
                errorColumns={errorColumns}
                parseUploadResult={parseUploadResult}
              />
            </TabPane>
          </Tabs>
        </Modal>
      </div>
    );
  }
}

Importer.propTypes = {
  modalOptions: React.PropTypes.object,  //弹窗相关参数
  templateOptions: React.PropTypes.object,  //模板相关参数，具体见./upload-file
  uploadOptions: React.PropTypes.object, //上传模板相关参数，具体见./upload-file
  asyncMode: React.PropTypes.bool, //是否是异步上传，若是
  asyncModeMessage:React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.node]), //异步上传的提示文案
  uploadResultOptions: React.PropTypes.object,
  onConfirmUpload: React.PropTypes.func,
  onValidate: React.PropTypes.func, //导入文件前额外的校验, 返回值类型 bool
  beforeUpload: React.PropTypes.func, //上传模板之前的钩子，参数为上传的文件，若返回 false 则停止上传，若返回处理后的文件，则继续上传
  infoMessage: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.node]),
  parseUploadResult: React.PropTypes.func, //导入结果文案
};

Importer.defaultProps = {
  modalOptions: {
    title: messages('common.import')/*导入*/
  },
  asyncMode: false,
  infoMessage: '',
  errorTableData: data => {
    return data && data.detailPage ? data.detailPage.content.map(i => {
      i.index = i.lineNumber;
      i.error = i.errorMessage;
      return i;
    }) : []
  },
  totalError: data => data && data.detailPage && data.detailPage.totalElements
    ? data.detailPage.totalElements
    : data.failureEntities
      ? data.failureEntities
      : 0,
  errorColumns: [
    {title: messages('common-1.key371')/*行号*/, dataIndex: 'index', width: '13%'},
    {title: messages('common-1.key372')/*错误信息*/, dataIndex: 'error',
      render: (text) => {
        return (
          <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        )
      }
    }
  ],
  btnProps: {
    type: 'primary'
  },
  btnName: messages('common.import')/*导入*/,
  parseUploadResult: uploadResult => messages('common-1.key377',{arg1: uploadResult.successEntities||0,arg2: uploadResult.failureEntities||0})/*导入成功：{arg1}条，导入失败：{arg2}条*/
};

Importer.getUploadResult = (data, type) => {
  let errorDetail = data.errors || (data.errorDetail ? JSON.parse(data.errorDetail) : {});
  let errorData = [];
  Object.keys(errorDetail).map(key => {
    if(Array.isArray(errorDetail[key])) {
      errorDetail[key].map(i => errorData.push({index: i, error: key}))
    } else {
      errorData.push({index: key, error: errorDetail[key]});
    }
  });
  return errorData;
};

export default Importer;
